/*
 * Copyright (C) 2014 luke.
 * 
 * This file is part of Silvie.
 * 
 * Silvie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Silvie is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Silvie.  If not, see <http://www.gnu.org/licenses/>.
 */

package silvie.resources.sprite;

import java.util.ArrayList;
import java.util.List;

import utils.DataReader;
import utils.PalettizedImage;

/**
 * AbstractSprite specialization for "RLE" (Run-Length Encoding) sprites. The
 * RLE used by Silver sprites applies to transparent pixels only.
 * 
 * @author luke
 * @see <a href="http://en.wikipedia.org/wiki/Run-length_encoding">Run-length
 *      encoding</a>
 */
public class RLESprite extends AbstractSprite {
	private static final int INITIAL_RLE_OFFSET = 4;

	/**
	 * RLESprite constructor.
	 * 
	 * @see AbstractSprite#AbstractSprite(byte[], int, int, int)
	 */
	public RLESprite(byte[] spritePalette, int size, int width, int height) {
		super(spritePalette, size, width, height);
	}

	@Override
	public void decode() {
		int currentPos = INITIAL_RLE_OFFSET;
		List<Short> indicesList = new ArrayList<Short>();
		for (int i = 0; i < super.palettizedImage.getHeight(); i++) {
			int rowSize = DataReader.readShort(super.spriteData, currentPos);
			currentPos += DataReader.SHORT_SIZE;
			byte[] rowBytes = new byte[rowSize];
			System.arraycopy(super.spriteData, currentPos, rowBytes, 0, rowSize);
			currentPos += rowSize;
			indicesList.addAll(getRowIndices(rowBytes));
		}
		short[] indices = new short[indicesList.size()];
		for (int i = 0; i < indicesList.size(); i++) {
			indices[i] = indicesList.get(i);
		}
		super.palettizedImage.setPixelIndices(indices);
	}

	/**
	 * Decodes a row of bytes from an RLE sprite's data.
	 * 
	 * @param rowBytes the RLE row bytes.
	 * @return a list of Shorts containing the pixel indices.
	 */
	private List<Short> getRowIndices(byte[] rowBytes) {
		List<Short> rowIndices = new ArrayList<Short>();
		for (int i = 0; i < rowBytes.length; i++) {
			int value = rowBytes[i]; // This is a signed value
			boolean transparent = value < 0;
			for (int j = 0; j < Math.abs(value); j++) {
				rowIndices.add((short) (transparent ? PalettizedImage.TRANSPARENT_INDEX : (rowBytes[++i] & 0xFF)));
			}
		}
		return rowIndices;
	}
}
